<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'

import type { FormInstance } from 'element-plus'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage,
  ElDatePicker
} from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { SUCCESS_CODE } from '@/constants'
import { addTaskResourceApi, updateTaskApi, taskInfoApi } from '@/api/task'
import { formatToDateTime } from '@/utils/dateUtil'

interface Props {
  type: string
  id: number
}

interface Emit {
  (e: 'handleOK'): void
}

const props = defineProps<Props>()

const emit = defineEmits<Emit>()

const visible = defineModel({ required: true, type: Boolean })

const { t } = useI18n()

const title = props.type === 'add' ? '添加任务' : '编辑任务'

const formRef = ref<FormInstance>()
const model = ref({
  name: null,
  describe: null,
  deadline: null
})

if (props.type === 'edit') {
  getInfo()
}

// const { required } = useValidator()
const rules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur']
    }
  ],
  deadline: [
    {
      required: true,
      message: '请选择截止时间',
      trigger: ['input', 'blur']
    }
  ]
}

const loading = ref(false)

function handleCancel() {
  visible.value = false
}

async function handleAjax() {
  try {
    const data = JSON.parse(JSON.stringify(model.value))
    data.deadline = formatToDateTime(data.deadline)

    let response
    if (props.type === 'add') {
      response = await addTaskResourceApi(data)
    } else {
      response = await updateTaskApi(data)
    }

    if (response.code === SUCCESS_CODE) {
      emit('handleOK')
      ElMessage.success(t('common.success'))
      handleCancel()
    }
    loading.value = false
  } finally {
    loading.value = false
  }
}

async function handleSubmit(formEl: FormInstance | undefined) {
  loading.value = true
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    loading.value = false
    if (valid) {
      handleAjax()
    } else {
      console.log('error submit!', fields)
    }
  })
}

async function getInfo() {
  const response = await taskInfoApi({ id: props.id })
  if (response.code === SUCCESS_CODE) {
    model.value = response.data
  }
}
</script>

<template>
  <ElDialog v-model="visible" :title="title">
    <ElForm
      ref="formRef"
      :model="model"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      :style="{ padding: '0px 20px' }"
    >
      <ElFormItem prop="name" label="名称">
        <ElInput v-model="model.name" clearable :placeholder="'请输入名称'" />
      </ElFormItem>
      <ElFormItem prop="deadline" label="截止时间">
        <ElDatePicker v-model="model.deadline" type="datetime" placeholder="请选择到期时间" />
      </ElFormItem>
      <ElFormItem prop="describe" label="描述">
        <ElInput v-model="model.describe" type="textarea" :rows="4" placeholder="请输入描述信息" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel"> 取消 </el-button>
        <el-button type="primary" @click="handleSubmit(formRef)"> 确定 </el-button>
      </div>
    </template>
  </ElDialog>
</template>
